package com.hopedove.yieldmanage.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.hopedove.utils.ParseUtils;
import com.hopedove.view.SimpleDialog;
import com.hopedove.yieldmanage.R;
import com.hopedove.yieldmanage.entity.InitEntity;
import com.hopedove.yieldmanage.entity.ProductEntity;
import com.hopedove.yieldmanage.net.IServiceImpl;
import com.hopedove.yieldmanage.net.RequestServiceImpl;
import com.hopedove.yieldmanage.utils.SharedPreUtil;

import org.json.JSONObject;

public class BangChengZActivity extends MIP_BaseActivity implements View.OnClickListener {
    /** 工号 **/
    private TextView mJubNumTv;
    /** 班次 **/
    private TextView mClassesTv;
    /** 保存 **/
    private Button mSaveBtn;
    /** 合计匹数 **/
    private TextView mTodayCountTv;
    /** 三联单号 **/
    private EditText editbizno;
    /** 称重重量 **/
    private EditText mFinishWeightEt;
    /** 工号1 **/
    private TextView mEmpNo1Et;
    /** 格数1 **/
    private TextView mCellNo1Et;
    /** 工号2 **/
    private TextView mEmpNo2Et;
    /** 格数2 **/
    private TextView mCellNo2Et;
    /** 工号3 **/
    private TextView mEmpNo3Et;
    /** 格数3 **/
    private TextView mCellNo3Et;
    /** 布号 **/
    private TextView mClothNoTv;
    /** 车号 **/
    private TextView chehaoTv;
    /** 类别 **/
    private TextView mClothTypeTv;
    /** 合约号 **/
    private TextView mContactNoTv;
    /** 批号1 **/
    private TextView mBatchNo1Tv;
    /** 批号2 **/
    private TextView mBatchNo2Tv;
    /** 圆筒 **/
    private TextView mCytubeTv;
    /** 尺寸 **/
    private TextView mClothSizeTv;
    /** 备注 **/
    private TextView beizhuTv;

    /** 合计匹数 **/
    private String mTodayCount = "";
    /** 偏差范围 **/
    private String mRange = "";
    /** 班次 **/
    private String mClasses = "";
    /** 工号 **/
    private String mJobNum = "";
    /** 页面初始化信息 **/
    private InitEntity mInit;
    /** 布票重量，隐藏参数 **/
    private String mClothWeight = "";
    /** 记录三联单号 **/
    private String mClothTktNo;
    /** 胚布实体类 **/
    private ProductEntity mProduct = new ProductEntity();


    private boolean isCorrect;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_chengzhong);
        initView();
        getInitInfo();

    }
    private void initView() {
        mSaveBtn = (Button) findViewById(R.id.saveBtn);
        mJubNumTv = (TextView) findViewById(R.id.jobNumTv);
        mClassesTv = (TextView) findViewById(R.id.classesTv);
        mTodayCountTv = (TextView) findViewById(R.id.todayCountTv);
        editbizno = (EditText) findViewById(R.id.editbizno);
        mFinishWeightEt = (EditText) findViewById(R.id.weightEt);
        mEmpNo1Et = (TextView) findViewById(R.id.jobNum1Et);
        mCellNo1Et = (TextView) findViewById(R.id.frames1Et);
        mEmpNo2Et = (TextView) findViewById(R.id.jobNum2Et);
        mCellNo2Et = (TextView) findViewById(R.id.frames2Et);
        mEmpNo3Et= (TextView) findViewById(R.id.jobNum3Et);
        mCellNo3Et=(TextView) findViewById(R.id.frames3Et);

        chehaoTv = (TextView) findViewById(R.id.chehaoTv);
        beizhuTv = (TextView) findViewById(R.id.beizhuTv);
        mClothNoTv = (TextView) findViewById(R.id.clothNoTv);
        mContactNoTv = (TextView) findViewById(R.id.contactNoTv);
        mClothTypeTv = (TextView) findViewById(R.id.clothTypeTv);
        mBatchNo1Tv = (TextView) findViewById(R.id.batchNo1Tv);
        mBatchNo2Tv = (TextView) findViewById(R.id.batchNo2Tv);
        mCytubeTv = (TextView) findViewById(R.id.cytubeTv);
        mClothSizeTv = (TextView) findViewById(R.id.clothSizeTv);

        mJobNum = (String) SharedPreUtil.getValue(this, SharedPreUtil.YHMC, "");
        mJubNumTv.setText(mJobNum);
        mSaveBtn.setOnClickListener(this);
        editbizno.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null
                        && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                        && event.getAction() == KeyEvent.ACTION_UP) {
                    String monadNo = editbizno.getText().toString().trim();
                    if (monadNo.length() >= 4) {
                        //type="0";//新增
                        startGetProductInfo();
                    } else {
                        SimpleDialog.show(BangChengZActivity.this, "三联单号格式不正确，请重新扫描！");
                    }
                    return true;
                }
                return false;
            }
        });


        editbizno.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                     clearProductInfo();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mFinishWeightEt.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null
                        && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                        && event.getAction() == KeyEvent.ACTION_UP) {
                    checkWeight();
                    return true;
                }
                return false;
            }
        });

        mFinishWeightEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isCorrect = false;
                if (s == null) {
                    return;
                }
                String temp = s.toString();
                int posDot = temp.indexOf(".");
                int index = mFinishWeightEt.getSelectionStart();
                if (posDot >= 0 && temp.length() - 2 > posDot) {
                    s.delete(index - 1, index);
                }
            }
        });

    }


    /**
     * 检查称重重量
     */
    private boolean checkWeight() {

        isCorrect = true;

        try {

            double weight = Double.parseDouble(mFinishWeightEt.getText().toString().trim());
            if (weight > 110) {

                SimpleDialog.show(this, "称重重量不得超过110！", new SimpleDialog.OnPositiveClickListener() {

                    @Override
                    public void onPositiveClick() {
                        // TODO Auto-generated method stub
                        mFinishWeightEt.setText("");
                        mFinishWeightEt.requestFocus();

                    }
                });
                isCorrect = false;
                return isCorrect;
            }

            if (weight < 1) {
                SimpleDialog.show(this, "称重重量不得小于1!", new SimpleDialog.OnPositiveClickListener() {

                    @Override
                    public void onPositiveClick() {
                        // TODO Auto-generated method stub
                        mFinishWeightEt.setText("");
                        mFinishWeightEt.requestFocus();

                    }
                });
                isCorrect = false;
                return isCorrect;
            }

            double range = Double.parseDouble(mRange);
            double clothWeight = Double.parseDouble(mClothWeight);

            if (weight < (1 - range) * clothWeight || weight > (1 + range) * clothWeight) {

                SimpleDialog.show(BangChengZActivity.this, "称重重量与布票重量偏差过大，是否继续保存？", new SimpleDialog.OnNegativeClickListener() {

                    @Override
                    public void onNegativeClick() {
                        mFinishWeightEt.setText("");
                        mFinishWeightEt.requestFocus();
                        isCorrect = false;
                    }
                }, new SimpleDialog.OnPositiveClickListener() {

                    @Override
                    public void onPositiveClick() {
                        isCorrect = true;
                    }
                });
            }
        } catch (NumberFormatException e) {

        }
        return isCorrect;
    }

    /***
     * 清除edittext焦点
     */
//    private void clearAllFocus() {
//        editbizno.clearFocus();
//        mFinishWeightEt.clearFocus();
//    }

    /**
     * 根据product对象显示详细信息
     *
     * @param product
     */
    private void showProductInfo(ProductEntity product) {

        mClothWeight = product.CLOTHWEIGHT;
        // toast(mClothWeight + "");

        mFinishWeightEt.setText(product.FINISHWEIGHT);

        mEmpNo1Et.setText(product.EMPNO1);

        mCellNo1Et.setText(product.CELLNO1);

        mEmpNo2Et.setText(product.EMPNO2);

        mCellNo2Et.setText(product.CELLNO2);

        mClothNoTv.setText(product.BH_ZZ);

        mEmpNo3Et.setText(product.EMPNO3);
        mCellNo3Et.setText(product.CELLNO3);

        mContactNoTv.setText(product.CONTACTNO);

        mClothTypeTv.setText(product.CLOTHTYPE);



        mBatchNo1Tv.setText(product.BATCHNO1);

        mBatchNo2Tv.setText(product.BATCHNO2);

        mCytubeTv.setText(product.CYTUBE);

        mClothSizeTv.setText(product.CLOTHSIZE);

        chehaoTv.setText(product.MACHINENO);
        beizhuTv.setText(product.REMARK);


    }

    /**
     * 清空界面信息
     */
    private void clearProductInfo() {

        mEmpNo1Et.setText("");

        mCellNo1Et.setText("");

        mEmpNo2Et.setText("");

        mCellNo2Et.setText("");
        mEmpNo3Et.setText("");

        mCellNo3Et.setText("");

        mClothNoTv.setText("");



        mContactNoTv.setText("");

        mClothTypeTv.setText("");



        mBatchNo1Tv.setText("");

        mBatchNo2Tv.setText("");

        mCytubeTv.setText("");

        mClothSizeTv.setText("");

        chehaoTv.setText("");
        beizhuTv.setText("");


    }

    /**
     * 准备获取胚布详细信息
     */
    private void startGetProductInfo() {
        mClothTktNo = editbizno.getText().toString().trim();
        if (TextUtils.isEmpty(mClothTktNo)) {
            SimpleDialog.show(this, "三联单号不能为空！",new SimpleDialog.OnPositiveClickListener() {

                @Override
                public void onPositiveClick() {
                    editbizno.requestFocus();

                }
            });
            //
            // mClothTktNoEt.findFocus();
            return;
        }
        getProductInfo(mClothTktNo);
    }

    /**
     * 准备新增胚布信息
     */
    private void startAddProduct() {
        mClothTktNo = editbizno.getText().toString().trim();
        String finishWeight = mFinishWeightEt.getText().toString();
        String empNo1 = mEmpNo1Et.getText().toString();
        String cellNo1 = mCellNo1Et.getText().toString();
//        String empNo2 = mEmpNo2Et.getText().toString();
//        String cellNo2 = mCellNo2Et.getText().toString();

        if (TextUtils.isEmpty(mClothTktNo)) {
            SimpleDialog.show(this, "三联单号不能为空！");
            editbizno.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(finishWeight)) {
            SimpleDialog.show(this, "称重重量不能为空！");
            mFinishWeightEt.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(empNo1)||TextUtils.isEmpty(cellNo1)) {
            SimpleDialog.show(this, "该三联号挡车工没有维护！");
            //mEmpNo1Et.requestFocus();
            return;
        }

        if(!isCorrect){
            double weight = Double.parseDouble(mFinishWeightEt.getText().toString().trim());
            if (weight > 110) {
                SimpleDialog.show(this, "称重重量不得超过110！");
                mFinishWeightEt.setText("");
                mFinishWeightEt.requestFocus();
                return;
            }
            if (weight < 1) {
                SimpleDialog.show(this, "称重重量不得小于1!");
                mFinishWeightEt.setText("");
                mFinishWeightEt.requestFocus();
                return;
            }

            double range = Double.parseDouble(mRange);
            double clothWeight = Double.parseDouble(mClothWeight);
            if (weight < (1 - range) * clothWeight || weight > (1 + range) * clothWeight) {
                SimpleDialog.show(BangChengZActivity.this, "称重重量与布票重量偏差过大，是否继续保存？", new SimpleDialog.OnNegativeClickListener() {

                    @Override
                    public void onNegativeClick() {
                        mFinishWeightEt.setText("");
                        mFinishWeightEt.requestFocus();

                    }
                }, new SimpleDialog.OnPositiveClickListener() {

                    @Override
                    public void onPositiveClick() {
                        mProduct.FINISHWEIGHT = finishWeight;
                        mProduct.EMPNO1 = empNo1;
                        mProduct.CELLNO1 = cellNo1;
                        getIsStandard(mClothTktNo);
                    }
                });
            }
        }else{
            mProduct.FINISHWEIGHT = finishWeight;
            mProduct.EMPNO1 = empNo1;
            mProduct.CELLNO1 = cellNo1;
            getIsStandard(mClothTktNo);
        }
    }


    /**
     * 页面初始化统计当日匹数与重量
     */
    private void getInitInfo() {
        showWait();
        String userBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "");
        RequestServiceImpl.getInitInfo(mMIPHandler, IServiceImpl.GETINITINFO_R, userBean);
    }

    /**
     * 获取产品详细参数
     */
    private void getProductInfo(String clothTktNo) {
        showWait();
        RequestServiceImpl.getProductInfo(mMIPHandler, IServiceImpl.GETPRODUCTINFO_R, clothTktNo);
    }

//    private void getIsExists(String clothTktNo) {
//        showWait();
//        RequestServiceImpl.getIsExists(mMIPHandler, IServiceImpl.GETISEXISTS_R, clothTktNo);
//    }

    private void getIsStandard(String clothTktNo) {
        showWait();
        RequestServiceImpl.getIsStandard(mMIPHandler, IServiceImpl.GETISSTANDARD_R, clothTktNo);
    }

    /**
     * 新增胚布信息
     *
     * @param product
     */
    private void addProduct(ProductEntity product) {
        showWait();
        String userBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "");
        RequestServiceImpl.addProduct(mMIPHandler, IServiceImpl.ADDPRODUCT_R, userBean, product);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.saveBtn) {// mClothTktNo = mClothTktNoEt.getText().toString().trim();
            // getIsStandard(mClothTktNo);
            startAddProduct();
        }

    }

//    @Override
//    public boolean dispatchKeyEvent(KeyEvent event) {
//        // toast("dispatchKeyEvent" + event.getKeyCode() + "");
//        // 拦截物理键盘事件
//        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
//            if (event.getAction() == KeyEvent.ACTION_DOWN) {
//                // mScanGun.isMaybeScanning(event.getKeyCode(), event);
//                return true;
//            }
//            return true;
//        }
//        return super.dispatchKeyEvent(event);
//    }

    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error) {
        stopWait();
        String msg = "";
        String opt = "";
        if (error) {
            switch (requestType) {
                case IServiceImpl.GETINITINFO_R:
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("MSG_INFO");
                        opt = jsonObj.optString("OPT_FLAG");
                        if ("SUCCESS".equals(opt)) {
                            mInit = ParseUtils.parse(objBody.toString(), InitEntity.class);
                            mTodayCount = mInit.HJPS;
                            mRange = mInit.pcfw;
                            mClasses = mInit.BC;
                            mClassesTv.setText(mClasses);
                            mTodayCountTv.setText(mTodayCount);

                        } else {

                            if (TextUtils.isEmpty(msg)) {
                                SimpleDialog.show(this, "出错");
                            } else {
                                SimpleDialog.show(this, msg);
                            }


                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case IServiceImpl.GETPRODUCTINFO_R:
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("MSG_INFO");
                        opt = jsonObj.optString("OPT_FLAG");
                        if ("SUCCESS".equals(opt)) {
                            mProduct = ParseUtils.parse(jsonObj.optJSONObject("DATA").toString(), ProductEntity.class);
                            // 设置班次
                            mProduct.PROCLASS = mClasses;
                            showProductInfo(mProduct);
                            mFinishWeightEt.requestFocus();
                        }else{
                            if (TextUtils.isEmpty(msg)) {
                                SimpleDialog.show(this, "出错");
                            } else {
                                SimpleDialog.show(this, msg);
                            }
                            editbizno.requestFocus();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case IServiceImpl.GETISSTANDARD_R:
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("MSG_INFO");
                        opt = jsonObj.optString("OPT_FLAG");
                        if ("SUCCESS".equals(opt)) {
                            // 这一步成功的情况下再去掉新增的方法
                            addProduct(mProduct);
                        }else{
                            if (TextUtils.isEmpty(msg)) {
                                SimpleDialog.show(this, "出错");
                            } else {
                                SimpleDialog.show(this, msg);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
//                case IServiceImpl.GETISEXISTS_R:
//                    try {
//                        JSONObject jsonObj = new JSONObject((String) objBody);
//                        msg = jsonObj.optString("MSG_INFO");
//                        opt = jsonObj.optString("OPT_FLAG");
//                        if ("SUCCESS".equals(opt)) {
//                            // 这一步成功的情况下再去掉新增的方法
//                            addProduct(mProduct);
//
//                        }else{
//                            if (TextUtils.isEmpty(msg)) {
//                                SimpleDialog.show(this, "出错");
//                            } else {
//                                SimpleDialog.show(this, msg);
//                            }
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    break;
                case IServiceImpl.ADDPRODUCT_R:
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("MSG_INFO");
                        opt = jsonObj.optString("OPT_FLAG");
                        if ("SUCCESS".equals(opt)) {
                            // 新增成功！
                            SimpleDialog.show(this, msg);
                            // 重新调用初始化页面信息接口
                            getInitInfo();
                            clearProductInfo();
                            editbizno.setText("");
                            mFinishWeightEt.setText("");

                            // mClothTktNoEt.setFocusable(true);
                            // mClothTktNoEt.setFocusableInTouchMode(true);

                            editbizno.requestFocus();
                            isCorrect=false;
                            // mClothTktNoEt.findFocus();

                        }else{
                            if (TextUtils.isEmpty(msg)) {
                                SimpleDialog.show(this, "出错");
                            } else {
                                SimpleDialog.show(this, msg);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        } else {
            switch (requestType) {
                case IServiceImpl.GETINITINFO_R:
                    toast("初始化数据失败！");
                    break;
                case IServiceImpl.GETPRODUCTINFO_R:
                    toast("查询失败！");
                    break;
            }
        }

    }



}
